//
//  NewsViewController.m
//  B-72K
//  Created by sos on 16/3/7.
//  Copyright © 2016年 sos. All rights reserved.
//
#import "NewsOtherViewController.h"
#import "NewsViewController.h"
#import "MyLoopsView.h"
#import "LunboModel.h"
#import "NewsTableViewCell.h"
#import <Masonry.h>
#import "ViewController.h"
#import "QPNetWorkingTool.h"
#import "NextDetialViewController.h"
#import <MJRefresh.h>
#import "SearchViewController.h"
#import "AllPrefixHeader.pch"
#import "BrowesModel.h"
#import "DataBaseManager.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface NewsViewController ()<UITableViewDelegate, UITableViewDataSource, DrawerViewControllerDelegate>
{
    ViewController *vc;
    UINavigationController *NC;
}
@property (nonatomic, strong)NSMutableArray *tableArr; // tableVIew数组
@property (nonatomic, strong)NSMutableArray *lunboArr; // 轮播图数组
@property (nonatomic, strong)UILabel *NaviLable;
@property (nonatomic,strong)MyLoopsView  *loopsView;
@property (nonatomic, retain) NSMutableArray *lunArr;/**< 轮播图数据数组 */
@property (nonatomic, retain) UIView *lunboView;/**< 轮播图所在 */
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, retain)NewsModel *newsModel;



@end
@implementation NewsViewController

+(NewsViewController *)shareDefults
{
    static NewsViewController *news;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        news = [[NewsViewController alloc]init];
    });
    return news;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.Str = @"all";
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"主页";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)];
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self dataHandler];
    [self creatTableView];
    [self creatlunbo];
    [self CreatNavi];
    [self addNotificationCenter];
    [self refresh];
    [self loading];
#pragma mark 1.实例化VC对象
    vc = [[ViewController alloc] init];
    vc.delegate = self;
#pragma mark 2.通过给定方法返回一个导航控制器
    NC = [vc getDrawerWithNavigationControllerBySize:CGSizeMake(220, [UIScreen mainScreen].bounds.size.height) forShowStyle:DrawerViewControllerShowStyleLeft andShowType:DrawerViewControllerShowTypeTableView withShowDetailStyle:DrawerViewControllerShowDetailStylePictureWithText isWithCoverView:YES canMove:YES] ;
#pragma mark 3.添加视图的层级关系(必须)
    [self.view addSubview:NC.view];
    [self addChildViewController:NC];
#pragma mark 4.行高和代理
    vc.rowHeight = 100;
    vc.delegate = self;
   }

#pragma mark - 下拉刷新
- (void)refresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //延迟2秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
                       dispatch_get_main_queue(),^{
                           
                           // 刷新
                           [self creatlunbo];
                           [self dataHandler];
                           //新版本是 MJ_header
                           [self.newsTableView.mj_header endRefreshing];
                       });
    }];
    self.newsTableView.mj_header = header;
    header.stateLabel.font = [UIFont systemFontOfSize:12];
}
- (void)loading
{
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //延迟两秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            // 非活动
            [QPNetWorkingTool getNetWorkingTool:[NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news?pageSize=20&lastId=%@&columnId=all&pagingAction=down", _newsModel.feedId] dic:nil success:^(id result) {
                NSMutableArray *arr = result[@"data"][@"data"];
                NSMutableArray *tempArr = [NewsModel modelHanderWithArray:arr];
                // 新数据添加到dataArr里
                for (NewsModel *m in tempArr) {
                    [self.tableArr addObject:m];
                }
                
                [_newsTableView reloadData];
            } fail:^(NSError *error) {
                
            }];
            
            [_newsTableView.mj_footer endRefreshing];
        });
    }];
    _newsTableView.mj_footer = footer;
}




// 创建导航栏和抽屉的按钮
- (void)CreatNavi
{
    self .button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setImage:[UIImage imageNamed:@"caidan2"] forState:UIControlStateNormal];
//    [_button setTitle:@"推出" forState:UIControlStateNormal];
    _button.frame = CGRectMake(0, 0, 50, 50);
    [_button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    self.navigationController.navigationBar.tintColor = [UIColor blueColor];
    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:self.button];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(Cancel)];
    self.navigationItem.leftBarButtonItem = button;
}
- (void)Cancel
{
    NSLog(@"sdfsdj");
    [vc showWithDuration:0.3f];
}
-(void)tiao
{
    NewsOtherViewController *vb = [[NewsOtherViewController alloc] init];
        vb.Str = self.Str;
    [self.navigationController pushViewController:vb animated:NO];
}
- (void)push
{
    [vc showWithDuration:0.3f];

}
- (void)dataHandler
{
    NSString *s = @"https://rong.36kr.com/api/mobi/news?pageSize=20&columnId=all&pagingAction=up";
    [QPNetWorkingTool getNetWorkingTool:s dic:nil success:^(id result) {
        self.tableArr = [NewsModel modelHanderWithArray:result[@"data"][@"data"]];
        [self.newsTableView reloadData];
    } fail:^(NSError *error) {
    }];
}
- (void)statusBarPositionChange:(NSNotification *)noti
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        [self landscape];
    } else if (orientation == UIInterfaceOrientationLandscapeRight) {

        [self landscape];
    } else if (orientation == UIInterfaceOrientationPortrait) {
        [self portrait];
    }
}

// 竖屏
- (void)portrait
{
        [self.lunboView removeFromSuperview];
    _newsTableView.frame = CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height);
    self.loopsView.frame =CGRectMake(0, 0, self.view.frame.size.width, 200);
    self.loopsView.frame =CGRectMake(0, 0, self.view.frame.size.width, 200);
    [self creatlunbo];
}
// 横屏
- (void)landscape
{
    UIView *img = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    img.backgroundColor = [UIColor whiteColor];
    [self.loopsView addSubview:img];
    [self.lunboView removeFromSuperview];
    [img removeFromSuperview];
    _newsTableView.frame = CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height);
    self.loopsView.frame =CGRectMake(0, 0, self.view.frame.size.width, 200);
    [self creatlunbo];
}
#pragma mark - 通知中心
- (void)addNotificationCenter
{
    // 监听屏幕旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarPositionChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
// 创建轮播图
- (void)creatlunbo
{
    NSString *str = @"https://rong.36kr.com/api/mobi/roundpics";
    [QPNetWorkingTool getNetWorkingTool:str dic:nil success:^(id result) {
        self.lunboArr = [NSMutableArray array];
        for (NSDictionary *dic in result[@"data"][@"pics"]) {
            [_lunboArr addObject:dic[@"imgUrl"]];
        }
        self.loopsView = [MyLoopsView myLoopsViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) imageArr:self.lunboArr];
        _loopsView.tag = 1000;
        self.newsTableView.tableHeaderView = _loopsView;
    } fail:^(NSError *error) {
        
    }];
}
// 创建tableView
- (void)creatTableView
{
    self.newsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _newsTableView.delegate = self;
    _newsTableView.dataSource = self;
//    _newsTableView.rowHeight = 250;
    [self.view addSubview:_newsTableView];
    [_newsTableView NightWithType:UIViewColorTypeNormal];
    [_newsTableView registerClass:[NewsTableViewCell class] forCellReuseIdentifier:@"newsCell"];
}

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    _newsModel = _tableArr.lastObject;
    return _tableArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsCell" forIndexPath:indexPath];
    [cell NightWithType:UIViewColorTypeNormal];
    cell.news = _tableArr[indexPath.row];
    return cell;
}
// cell 动画
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //cell动画
    if ([_tableArr count] != 0) {
        cell.frame = CGRectMake(-cell.frame.size.width, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        [UIView animateWithDuration:0.5 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        }];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NextDetialViewController *nwsdetial = [[NextDetialViewController alloc] init];
    
    NewsModel *m = _tableArr[indexPath.row];
    nwsdetial.str = m.feedId;
    nwsdetial.strr = m.title;
    
//    // 添加浏览数据
    BrowesModel *mm = [[BrowesModel alloc] init];
    mm.title = m.title;
    mm.feedId = m.feedId;
    
    [[DataBaseManager shareInstance] insertBrwose:mm];
    
    [self.navigationController pushViewController:nwsdetial animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)search
{
    SearchViewController *search = [[SearchViewController alloc]init];
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:search];
    [self presentViewController:navi animated:YES completion:^{
        
        
    }];
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
